package com.polaris.live.ui.me

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.adapter.level.MeRichCharmAdapter
import com.polaris.live.adapter.level.MeRichCharmBannerAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.FragmentMeRichCharmBinding
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.PreviewRichCharmPopup
import com.polaris.live.resp.back_resp.UserRichCharmConfigVo
import com.polaris.live.translation.R.string
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.viewmodel.me.RichCharmViewModel
import com.zhpan.bannerview.constants.PageStyle

/**
 * 我的壕等级和魅等级
 *
 * @author Created by 半仙 on 2024/9/18/018 14:50
 */
class MeRichCharmFragment : BaseVbFragment<RichCharmViewModel, FragmentMeRichCharmBinding>() {

    private val mType by lazy { arguments?.getString("type", RichCharmActivity.RICH) }

    private val mBannerAdapter by lazy { MeRichCharmBannerAdapter() }

    private val mAdapter by lazy { MeRichCharmAdapter() }

    private var mUserRichCharm: List<UserRichCharmConfigVo>? = null

    override fun initView(savedInstanceState: Bundle?) {
        ViewUtils.setMargin(
            mBinding.consBottom,
            bottomMargin = NavigationBarUtils.getNavigationBarHeight(requireContext())
        )
        mViewModel.getRichCharmV2()
        mBinding.bannerLevel.apply {
            registerLifecycleObserver(lifecycle)
            setAdapter(mBannerAdapter)
            setCanLoop(false)
            setPageMargin(30.autoDp)
            setRevealWidth(105.autoDp, 105.autoDp)
            setIndicatorVisibility(View.GONE)
            setPageStyle(PageStyle.MULTI_PAGE_SCALE, 0.85f)
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    val data = mUserRichCharm?.getOrNull(position)?.levelConfig ?: return
                    mAdapter.setList(data)
                    val richCharm = mUserRichCharm?.getOrNull(position) ?: return
                    onPageChangeCallback?.invoke(richCharm)
                }
            })
        }
        mBinding.levelRecycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
        }
        userData()
        initObserver()
        initListener()
        if (mType == RichCharmActivity.CHARM) {
            mBinding.tvRecharge.visibility = View.GONE
        }
    }

    fun getMaxLevel() {
        if (!isCreated()) {
            return
        }
        val position = mBinding.bannerLevel.currentItem
        val richCharm = mUserRichCharm?.getOrNull(position) ?: return
        onPageChangeCallback?.invoke(richCharm)
    }

    private fun initListener() {
        mBannerAdapter.setOnClickItemCallback { position, _ ->
            mBinding.bannerLevel.setCurrentItem(position, true)
        }
        mAdapter.setClickItem {
            PreviewRichCharmPopup.show(requireContext(), it)
        }
        mBinding.tvRecharge.setOnSingleClickListener {
            GlobalPopupManager.showRechargePopup(
                requireContext(),
                mViewModel,
                isNeedBottom = true,
                onRechargeOk = {
                    if (it == true) {
                        mViewModel.getUser()
                    }
                })
        }
    }

    private fun initObserver() {
        mViewModel.mUserLiveData.observe(this) { resultState ->
            parseState(resultState, {
                UserManager.setUser(it)
                userData()
            })
        }
        mViewModel.mRichCharmV2LiveData.observe(this) { resultState ->
            parseState(resultState, {
                mUserRichCharm = if (mType == RichCharmActivity.RICH) {
                    mAdapter.setType(AppConst.UserSex.MAN)
                    it.rich
                } else {
                    mAdapter.setType(AppConst.UserSex.WOMAN)
                    it.charm
                }
                mBinding.bannerLevel.create(mUserRichCharm)

                val data = mUserRichCharm?.getOrNull(0)?.levelConfig ?: return@parseState
                mAdapter.setList(data)

                userData()

            })
        }
    }

    private fun userData() {
        UserManager.getUser().account?.let { account ->
            val isRich = mType == RichCharmActivity.RICH
            val (level, nextNum, image) = if (isRich) {
                RichCharmImgUtil.getRichImg(account.richs)
            } else {
                RichCharmImgUtil.getCharmImg(account.charms)
            }

            val num =
                if (isRich) RichCharmImgUtil.getRichNum(account.richs) else RichCharmImgUtil.getCharmNum(account.charms)
            val currentLevel = if (level >= if (isRich) 200 else 100) level - 1 else level

            mBinding.tvLevelStart.text = "Lv.$currentLevel"
            mBinding.tvLevelEnd.text = "Lv.${currentLevel + 1}"

            val currentPoints = if (isRich) account.richs - num else account.charms - num
            val totalPoints = nextNum - num

            mBinding.progressBar.progress = if (totalPoints > 0) {
                (currentPoints * 100 / totalPoints).toInt()
            } else {
                100
            }

            mBinding.tvDiamond.text = if ((if (isRich) account.richs else account.charms) < nextNum) {
                (nextNum - (if (isRich) account.richs else account.charms)).toString()
            } else {
                "0"
            }

            mBinding.avHead.setImageUrl(UserManager.getUser().avatar, UserManager.getUserId())
            mBinding.tvNickName.text = UserManager.getUser().nickname
            if (isRich) {
                mBinding.widgetLevel.setRichsLevel(account.richs)
            } else {
                mBinding.widgetLevel.setCharmsLevel(account.charms)
            }
            mBinding.vipView.setVipLevel(UserManager.getUser().profile?.vipLevel)
            mUserRichCharm?.forEachIndexed { index, data ->
                if (currentLevel <= data.maxLevel && currentLevel >= data.minLevel) {
                    mBinding.bannerLevel.currentItem = index
                    mAdapter.setList(data.levelConfig)
                    onPageChangeCallback?.invoke(data)
                }
            }
            if (isRich) {
                mBinding.tvBeans.text = StringUtils.getString(string.diamond_string)
                mBinding.tvConsumption.text = StringUtils.getString(string.consumption)
                mBinding.ivDiamond.setImageResource(R.drawable.ic_diamond_small)
            } else {
                mBinding.tvBeans.text = StringUtils.getString(string.beans)
                mBinding.tvConsumption.text = StringUtils.getString(string.earn)
                mBinding.ivDiamond.setImageResource(R.drawable.ic_beans)
            }
        }
    }

    private var onPageChangeCallback: ((UserRichCharmConfigVo) -> Unit)? = null

    fun setOnPageChangeCallback(b: (UserRichCharmConfigVo) -> Unit) {
        onPageChangeCallback = b
    }
}